﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Yto.Common.Extensions
{
    public static class ListExtensions
    {
        public static DataTable ToDataTable<T>(this List<T> list)
        {
            DataTable dt = new DataTable();

            PropertyInfo[] proInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach(var p in proInfos)
            {
                dt.Columns.Add(p.Name, p.PropertyType);
            }

            foreach(T obj in list)
            {
                var values = new object[proInfos.Length];
                for(int i = 0; i < proInfos.Length; i++)
                {
                    values[i] = proInfos[i].GetValue(obj, null);
                }
                dt.Rows.Add(values);
            }

            return dt;
        }
    }
}
